#ifndef __NETCLIENT_H__
#define __NETCLIENT_H__
#include "cocos2d.h"
#include "cocos-ext.h"
#include "WebSocket.h"
#include "WebSocketCodec.h"
#include "MessageProcessor.h"
#include "SessionMessage.h"
USING_NS_CC;
USING_NS_CC_EXT;
class NetClient:public cocos2d::extension::WebSocket::Delegate
{
public:
	NetClient(void)
	{
		client=new WebSocket();
		codec=new WebSocketCodec();
	}
	virtual ~NetClient(void)
	{
		if (client)
			client->close();
	}//"ws://172.31.8.16:8002/websocket"
	void connect(const char* url){
		if (!client->init(*this,url))
		{
			CC_SAFE_DELETE(client);
		}
	}

	// Delegate methods
	void onOpen(cocos2d::extension::WebSocket* ws){
		CCLog("Websocket (%p) opened", ws);
		SessionMessage*  message= new SessionMessage(1);
		MessageProcessor::put(message);
	}
	void sendMessage(BaseMessage *message){
		codec->encode(message);
		client->send((unsigned char*)message->getBuffer(),message->getLength());
	}

	void onMessage(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::Data& data)
	{
		if (!data.isBinary)
		{
			CCLog("data type is wrong");
		}
		else
		{
			char times[100] = {0};
			std::string binaryStr = "response bin msg: ";
			BaseMessage* message=codec->decode((unsigned char *)data.bytes);
			MessageProcessor::put(message);
		}
	}

	void onClose(cocos2d::extension::WebSocket* ws){
		client=NULL;
		CC_SAFE_DELETE(ws);
	}

	void onError(cocos2d::extension::WebSocket* ws, const cocos2d::extension::WebSocket::ErrorCode& error)
	{
		CCLog("Error was fired, error code: %d", error);
	}

private:
	cocos2d::extension::WebSocket* client;
	WebSocketCodec* codec; 
};
#endif
